import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.of;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 导出结果
 * 
 * @author weiss
 *
 */
public class ExportResult implements Serializable, Callable<ExportResult> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String nodeCommand = "node /root/puppeteer/testdriven/src/main/resources/export_pdf/puppeteer_export_pdf.js";
	private static final String SUCCESS = "export pdf success";

	private boolean success;
	private String pdfPath;
	private String id;

	private String command;

	public ExportResult(String env, String reportType, String id) {
		super();
		this.id = id;
		this.pdfPath = of("/tmp/report_export_dir/", reportType, UUID.randomUUID().toString(), ".pdf")
				.collect(joining());

		this.command = of(nodeCommand, env, reportType, this.id, pdfPath).collect(joining(" "));
	}

	@Override
	public ExportResult call() throws Exception {
		try {
			// TimeUnit.SECONDS.sleep(new Random().nextInt(5));
			// System.out.println(LocalTime.now()+ " " +Thread.currentThread().getName());
			System.out.print(command);
			Process p = Runtime.getRuntime().exec(command);
			InputStream is = p.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedReader br = new BufferedReader(new InputStreamReader(bis, StandardCharsets.UTF_8));
			String result = br.lines().collect(joining("\n"));
			System.out.println(result);
			if (result != null && result.contains(SUCCESS)) {
				System.out.println("导出成功");
				this.success = true;
			} else {
				System.out.println("fail");
				this.success = false;
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getPdfPath() {
		return pdfPath;
	}

	public void setPdfPath(String pdfPath) {
		this.pdfPath = pdfPath;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}
